<template>
  <div class="table-page">
    <div class="header-stats">
      <div class="stat-item">
        <div class="stat-label">总部门数</div>
        <div class="stat-value">{{ totalDepartments }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">总人员数</div>
        <div class="stat-value">{{ totalEmployees }}</div>
      </div>
    </div>

    <GiTable
      row-key="id"
      title="组织架构"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: true, y: '100%', minWidth: 1000 }"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
      class="org-table"
      :row-class-name="getRowClassName"
      :stripe="true"
      :border="{ cell: true }"
      @refresh="search"
    >
      <template #custom-left>
        <div class="search-box">
          <a-input
            v-model="queryForm.name"
            placeholder="请输入部门/人员名称"
            allow-clear
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix><icon-search /></template>
          </a-input>
          <a-button @click="reset">重置</a-button>
        </div>
      </template>
      <template #custom-right>
        <a-button type="primary" :loading="syncLoading" @click="onSyncOrg">
          <template #icon><icon-sync /></template>
          <template #default>同步组织架构</template>
        </a-button>
      </template>
      <template #type="{ record }">
        <a-tag
          :color="record.type === 'department' ? 'arcoblue' : 'green'"
          class="type-tag"
        >
          {{ record.type === 'department' ? '部门' : '人员' }}
        </a-tag>
      </template>
      <template #name="{ record }">
        <div class="name-cell" :style="{ paddingLeft: `${getIndent(record)}px` }">
          <span class="tree-icon">
            <icon-folder v-if="record.type === 'department'" />
            <icon-user v-else />
          </span>
          <span
            class="name-text"
            :class="{ 'department-name': record.type === 'department' }"
            :style="{
              color: record.color || (record.type === 'department' ? '#165DFF' : 'inherit'),
            }"
          >{{ record.name }}</span>
          <div
            v-if="record.type === 'department' && record.totalEmployeeCount > 0"
            class="employee-total-count"
            title="部门总人员数"
          >
            {{ record.totalEmployeeCount }}人
          </div>
        </div>
      </template>
    </GiTable>
  </div>
</template>

<script setup lang="ts">
import { cloneDeep, debounce } from 'lodash-es'
import { Message } from '@arco-design/web-vue'
import { computed, ref } from 'vue'
import { getOrganizationalStructure, searchOrganizationalStructure, syncOrganizationalStructure } from '@/apis/organization/framework'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { useTable } from '@/hooks'

defineOptions({ name: 'Meet' })

const queryForm = reactive({
  sort: ['createTime,desc'],
  name: ''
})

// 控制是否显示所属部门列
const showDeptName = computed(() => !!queryForm.name)

// 总统计数据
const totalDepartments = ref(0)
const totalEmployees = ref(0)

// 递归计算部门下所有人员数量（包括子部门的人员）
const calculateTotalEmployees = (node) => {
  if (!node.children || node.children.length === 0) {
    return node.type === 'user' ? 1 : 0
  }

  let count = 0
  for (const child of node.children) {
    if (child.type === 'department') {
      count += calculateTotalEmployees(child)
    } else {
      count += 1
    }
  }
  return count
}

const {
  tableData: dataList,
  loading,
  search,
  handleDelete: _handleDelete
} = useTable((page) => getOrganizationalStructure({ ...queryForm, ...page }), {
  immediate: true,
  formatResult(_data) {
    const dataList = cloneDeep(_data)

    // 重置统计
    totalDepartments.value = 0
    totalEmployees.value = 0

    // 第一次遍历：计算每个部门的总人员数（包括子部门的人员）
    function calculateEmployeeCounts(arr) {
      return arr.map((item) => {
        if (item.type === 'department') {
          if (item.children && item.children.length > 0) {
            // 计算直接人员数量（不包括子部门）仍然保留，但不显示
            const directEmployees = item.children.filter((child) => child.type !== 'department')
            item.directEmployeeCount = directEmployees.length

            // 计算总人员数量（包括子部门的人员）
            item.totalEmployeeCount = calculateTotalEmployees(item)

            // 处理子节点
            item.children = calculateEmployeeCounts(item.children)
          } else {
            item.directEmployeeCount = 0
            item.totalEmployeeCount = 0
          }
        }
        return item
      })
    }

    // 第二次遍历：设置样式和统计
    function processStyles(arr, parentColor, level = 0) {
      return arr.map((item) => {
        // 设置层级信息，用于缩进显示
        item.level = level

        // 如果是部门，继承父部门的颜色
        if (item.type === 'department') {
          // 部门数+1
          totalDepartments.value += 1

          item.color = item.color || parentColor

          if (item.children && item.children.length > 0) {
            // 更新总人员数（只在根部门添加，避免重复计算）
            if (level === 0) {
              totalEmployees.value += item.totalEmployeeCount
            }

            item.children = processStyles(item.children, item.color, level + 1)
          }
        } else {
          // 如果是用户，删除children
          delete item.children

          // 如果是顶层的用户，需要直接计入总人数
          if (level === 0) {
            totalEmployees.value += 1
          }
        }
        return item
      })
    }

    // 先计算人员数量
    const dataWithCounts = calculateEmployeeCounts(dataList)
    // 再处理样式和统计
    return processStyles(dataWithCounts, undefined)
  }
})

const columns: TableInstanceColumns[] = [
  { title: '部门/人员名称', dataIndex: 'name', slotName: 'name', width: 300 },
  { title: '类型', dataIndex: 'type', slotName: 'type', width: 100 },
  { title: '工号', dataIndex: 'workId', width: 120 },
  {
    title: '所属部门',
    dataIndex: 'deptName',
    width: 200,
    show: showDeptName.value
  }
]

// 获取行的类名
const getRowClassName = (record: any) => {
  return record.type === 'department' ? 'department-row' : 'employee-row'
}

// 获取缩进值
const getIndent = (record: any) => {
  return (record.level || 0) * 20
}

// 重置
const reset = () => {
  queryForm.name = ''
  search()
}

// 防抖处理搜索
const debouncedSearch = debounce(async (value: string) => {
  if (!value) {
    search()
    return
  }
  loading.value = true
  try {
    const res = await searchOrganizationalStructure(value)
    dataList.value = res.data || []
  } catch (error) {
    console.error(error)
    Message.error('搜索失败')
  } finally {
    loading.value = false
  }
}, 300)

// 搜索处理
const handleSearch = (value: string) => {
  debouncedSearch(value)
}

const syncLoading = ref(false)
const onSyncOrg = () => {
  syncLoading.value = true
  syncOrganizationalStructure().then((_res) => {
    Message.success('同步成功')
    syncLoading.value = false
  })
}
</script>

<style lang="scss" scoped>
.table-page {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  height: 100%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

  .header-stats {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

    .stat-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 12px 20px;
      background: white;
      border-radius: 6px;
      border-left: 4px solid #165DFF;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      &:last-child {
        border-left-color: #52c41a;
      }

      .stat-label {
        color: #86909c;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .stat-value {
        color: #1d2129;
        font-size: 24px;
        font-weight: 600;
      }
    }
  }

  .org-table {
    :deep(.arco-table-tr) {
      &:hover {
        background-color: var(--color-fill-2);
      }

      &.department-row {
        background-color: rgba(var(--primary-6), 0.05);

        &:hover {
          background-color: rgba(var(--primary-6), 0.1);
        }
      }

      &.employee-row {
        &:nth-child(even) {
          background-color: #fafafa;
        }
      }
    }

    :deep(.arco-table-th) {
      background-color: #f2f3f5;
      font-weight: 600;
    }
  }

  .search-box {
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 4px;

    .search-input {
      width: 300px;
      border-radius: 4px;

      :deep(.arco-input-wrapper) {
        background-color: #f9f9f9;

        &:hover {
          background-color: #fff;
          border-color: rgb(var(--primary-6));
        }
      }
    }
  }

  .name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;

    .tree-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 22px;
      height: 22px;
      color: #86909c;
    }

    .name-text {
      font-size: 14px;
      color: var(--color-text-1);

      &.department-name {
        font-weight: 600;
        font-size: 15px;
      }
    }

    .employee-total-count {
      background-color: #165DFF;
      color: white;
      padding: 0 8px;
      height: 22px;
      line-height: 22px;
      border-radius: 11px;
      font-size: 12px;
      font-weight: 500;
      display: inline-flex;
      align-items: center;
      margin-left: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }

  .type-tag {
    padding: 2px 10px;
    border-radius: 4px;
    font-weight: 500;
  }
}
</style>
